import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Button, Card, Input } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const FormItem = Form.Item;

@connect((state, ownProps) => {
    const { articles:  { entities } } = state
    const { match: { params: {id} } } = ownProps
    return {
        ...entities[id]
    } 
})
class Edit extends Component {

    componentDidMount() {
        const { match: { params: { id }} } = this.props
        const { id: articleId } = this.props
        if(!articleId){
            this.props.dispatch({
                type: 'articles/getArticleById',
                articleId: id
            })
        }
        
    }

	saveHandler = e => {
		e.preventDefault();
		this.props.form.validateFieldsAndScroll((err, values) => {
			if (!err) {
				this.props.dispatch({
					type: 'articles/updateArticle',
					payload: values
				})
			}
		});
	};

    render() {
        const { title, content } = this.props
		const { getFieldDecorator: gtd } = this.props.form;
		const itemLayout = {
			labelCol: {
				xs: {span: 24},
				sm: {span: 7}
			},
			wrapperCol: {
				xs: {span: 24},
				sm: {span: 17},
				
			}
		}
        return (
            <PageHeaderLayout
                title="Edit articles"
                //content="123"
            >
                <Card bordered={false}>
					<Form onSubmit={this.saveHandler}>
						<FormItem {...itemLayout} label="Title">
							{
								gtd("Title", {
									rules: [
										{
                                            initialValue: {title},
											required: true,
											message: 'Please input Title.'
										}
									]
								})(<Input/>)
							}
						</FormItem>
						<FormItem {...itemLayout} label="Content">
							{
								gtd("Content", {
									rules: [
										{
											required: true,
											message: 'Please input content.'
										},
										{
											min: 10,
											message: 'Least 10 words.'
										}
									]
								})(<Input.TextArea autosize={{minRows: 10}}/>)
							}
						</FormItem>
						<FormItem wrapperCol={{span: 8, offset: 7}}>
							<Button type="primary" size="large" htmlType="submit">
								Save
							</Button>
						</FormItem>
					</Form>
                </Card>
            </PageHeaderLayout>
        )
    }
}

export default Form.create()(Edit) 